﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;
using System.Text.RegularExpressions;
using System.Data.OleDb;
namespace Congducsan
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }
        
        // Khai báo biến toàn cục
        DBAcces dbLytrinh;
        DBAcces dbLoaicong;
        public DataSet dsLT = new DataSet();
        bool loadedRcFile = false;
        
        //sự kiện load form main
        private void FrmMain_Load(object sender, EventArgs e)
        {
            loadRecentFile();   
        }

        //Kiểm tra kết nối
        private bool checkConnectFromDb(string FilePath)
        {
            dbLytrinh = new DBAcces(FilePath);
            dbLoaicong = new DBAcces(FilePath);
            if (dbLytrinh.checkConnect==false||dbLoaicong.checkConnect==false)
            {
                return false;
            }
            return true;
        }

        //Load dữ liệu từ file database lên datagridview
        private void loadFileInDgv(string FilePath)
        {
            if (checkConnectFromDb(FilePath))
            {
                RegistryKey regKey = Registry.CurrentUser;
                regKey = regKey.CreateSubKey("Software\\HaithanhSoft\\Drad2012\\Congducsan");
                regKey.SetValue("File", FilePath.Trim());
                saveRecentFile();
                loadRecentFile();
                this.Text = "Gioithieu - Cống đúc sẵn - ";

                dataGridView1.Columns.Clear();
                dataGridView1.Enabled = true;
                BindingSource bs = new BindingSource();

                dbLytrinh.getDataSet("select Lytrinh,Id_Loaicong From tb_Lytrinh");
                DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
                bs.DataSource = dbLytrinh.ds.Tables["Table"];
                bindingNavigator1.BindingSource = bs;
                dataGridView1.DataSource = bs;
                dataGridView1.Columns[0].DisplayIndex = 0;
                dataGridView1.Columns[0].Width = 180;
                dataGridView1.Columns[1].Visible = false;
                dataGridView1.Columns[0].Name = "Lytrinh";
                dataGridView1.Columns[0].HeaderText = "Lý trình";
                dbLoaicong.getDataSet("select ID,Ten from tb_Loaicong");
                cmb.HeaderText = "Loại cống";
                cmb.Width = 600;
                cmb.MaxDropDownItems = 10;
                cmb.DataSource = dbLoaicong.ds.Tables["Table"];
                cmb.DisplayMember = "Ten";
                cmb.ValueMember = "ID";
                cmb.Name = "IdLoaicong";
                cmb.DataPropertyName = "Id_Loaicong";
                dataGridView1.Columns.Add(cmb);
                dataGridView1.Columns[2].DisplayIndex = 1;

                //Gan du lieu cho bien toan cuc dsLT
                dsLT = dbLytrinh.ds;
            }
            else
            {
                MessageBox.Show("File dữ liệu không phù hợp");
            }
        }

        //mở hộp thoại New file
        private void menuNew_Click(object sender, EventArgs e)
        {
            RegistryKey regKey = Registry.CurrentUser;
            regKey = regKey.CreateSubKey("Software\\HaithanhSoft\\Drad2012\\Congducsan");
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "Data files (*.mdb)|*.mdb";
            saveDialog.InitialDirectory = @"C:\";
            saveDialog.RestoreDirectory = true;
            saveDialog.Title = "Tạo file dữ liệu mới";
            string pathNewFile = "";
            if (saveDialog.ShowDialog()==DialogResult.OK)
            {
                string pathOldFile = Directory.GetCurrentDirectory() + @"\dbCongducsan.mdb";
                pathNewFile = saveDialog.FileName;
                try
                {
                    string pathSourcesFile = Directory.GetCurrentDirectory() + @"\dbCongducsan.mdb";
                    if (pathSourcesFile.Trim() == pathNewFile.Trim())
                    {
                        MessageBox.Show("Không thể ghi đè vào file Dữ liệu gốc!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        menuNew_Click(sender, e);
                    }
                    else
                    {
                        File.Copy(pathOldFile, pathNewFile, false);
                        loadFileInDgv(pathNewFile);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        //mở hộp thoại Open file
        private void menuOpen_Click(object sender, EventArgs e)
        {
            
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "Data files (*.mdb)|*.mdb";
            openDialog.Title = "Mở file dữ liệu ";
            openDialog.Multiselect = false;
            openDialog.RestoreDirectory = true;
            string file = "";
            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                file = openDialog.FileName;
                loadFileInDgv(file);
            }
        }

        // mở hộp thoại Save As file
        private void menuSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();
            RegistryKey regKey=Registry.CurrentUser;
            regKey=regKey.CreateSubKey("Software\\HaithanhSoft\\Drad2012\\Congducsan");
            saveDialog.Filter = "Data files (*.mdb)|*.mdb";
            saveDialog.Title = "Save as file dữ liệu";
            saveDialog.InitialDirectory = @"C:\Users\Quynh\Documents";
            saveDialog.RestoreDirectory = true;
            if (saveDialog.ShowDialog()==DialogResult.OK)
            {
                string pathOldFile = regKey.GetValue("File").ToString();
                string pathNewFile = saveDialog.FileName;
                string pathSourcesFile = Directory.GetCurrentDirectory() + @"\dbCongducsan.mdb";
                if (pathSourcesFile.Trim()==pathNewFile.Trim())
                {
                    MessageBox.Show("Không thể ghi đè vào file Dữ liệu gốc!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    menuSave_Click(sender, e);
                }
                else
                {
                    File.Copy(pathOldFile, pathNewFile);
                    loadFileInDgv(pathNewFile);
                }
                
            }
        }

        // Ghép khối lượng
        private void ghepKhoiLuong()
        {
            RegistryKey regKey = Registry.CurrentUser;
            regKey = regKey.CreateSubKey("Software\\HaithanhSoft\\Drad2012\\Congducsan");
            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Filter = "Data files (*.mdb)|*.mdb";
            openDialog.Title = "Mở file dữ liệu ";
            openDialog.Multiselect = false;
            openDialog.RestoreDirectory = true;
            string file = "";
            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                file = openDialog.FileName;
                string pathOldFle = regKey.GetValue("File").ToString();
                DBAcces dbCanGhep = new DBAcces(pathOldFle);
                DBAcces dbDuocChon = new DBAcces(file);
                if (dbCanGhep.checkConnect==true)
                {
                    try
                    {
                        //thêm dữ liệu cho bảng tb_Lytrinh
                        string sqlQuery = "SELECT *FROM tb_Lytrinh";
                        dbCanGhep.getDataSet(sqlQuery);
                        dbDuocChon.getDataSet(sqlQuery);
                        foreach (DataRow item in dbDuocChon.ds.Tables[0].Rows)
                        {
                            DataRow dr = dbCanGhep.ds.Tables[0].NewRow();
                            dr[0] = item[0];
                            dr[1] = item[1];
                            dbCanGhep.ds.Tables[0].Rows.Add(dr);

                        }
                        dbCanGhep.updateDataFull(sqlQuery);

                        //thêm dữ liệu cho bảng tb_KlCt
                        sqlQuery = "SELECT *FROM tb_KlCt ";
                        dbCanGhep.getDataSet(sqlQuery);
                        dbDuocChon.getDataSet(sqlQuery);
                        foreach (DataRow item in dbDuocChon.ds.Tables[0].Rows)
                        {
                            DataRow dr = dbCanGhep.ds.Tables[0].NewRow();
                            dr[0] = item[0];
                            dr[1] = item[1];
                            dbCanGhep.ds.Tables[0].Rows.Add(dr);

                        }
                        dbCanGhep.updateDataFull(sqlQuery);

                        //thêm dữ liệu cho bảng tb_Bieuthuc
                        sqlQuery = "SELECT *FROM tb_Bieuthuc";
                        dbCanGhep.getDataSet(sqlQuery);
                        dbDuocChon.getDataSet(sqlQuery);
                        foreach (DataRow item in dbDuocChon.ds.Tables[0].Rows)
                        {
                            DataRow dr = dbCanGhep.ds.Tables[0].NewRow();
                            dr[0] = item[0];
                            dr[1] = item[1];
                            dbCanGhep.ds.Tables[0].Rows.Add(dr);

                        }
                        dbCanGhep.updateDataFull(sqlQuery);

                        //Load lại datagridview
                        loadFileInDgv(pathOldFle);
                        MessageBox.Show("Ghép khối lượng thành công!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else
                {
                    MessageBox.Show("File dữ liệu không đúng định dạng", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            
        }
        // Lưu file vào recentFile
        private void saveRecentFile()
        {
            RegistryKey regKey = Registry.CurrentUser;
            regKey = regKey.CreateSubKey("Software\\HaithanhSoft\\Drad2012\\Congducsan");
            string File = regKey.GetValue("File").ToString();
            List<string> lsFile = new List<string>();
            for (int i = 1; i <= 4; i++)
            {
                string tmp = regKey.GetValue("File" + i.ToString()).ToString();
                lsFile.Add(tmp);
            }
            if (!lsFile.Contains(File))
            {
                lsFile.RemoveAt(3);
            }
            else
            {
                lsFile.Remove(File);
            }
            regKey.SetValue("File1", File.TrimStart());
            for (int i = 2; i <= 4; i++)
            {
                regKey.SetValue("File" + i.ToString(), lsFile[i - 2]);
            }
            regKey.Close();
        }

        //Load recent file
        private void loadRecentFile()
        {
            RegistryKey regKey = Registry.CurrentUser;
            regKey = regKey.CreateSubKey("Software\\HaithanhSoft\\Drad2012\\Congducsan");
            string str;
            int Vitri1 = 4;
            int Vitri2 = 5;
            int Stt = 1;
            if (loadedRcFile == true)
            {
                int countItem = menuFile.DropDownItems.Count;
                for (int i = 0; i <countItem - 6; i++)
                {
                    menuFile.DropDownItems.RemoveAt(Vitri1);
                }
            }
            ToolStripSeparator tsp = new ToolStripSeparator();
            menuFile.DropDownItems.Insert(4, tsp);
            for (int i = 1; i <= 4; i++)
            {
                if ((str=regKey.GetValue("File" + i.ToString()).ToString()).Trim() != "")
                {
                    ToolStripMenuItem tsm = new ToolStripMenuItem("&"+(Stt++).ToString()+"."+str);
                    tsm.Click += new EventHandler(tsm_Click);
                    menuFile.DropDownItems.Insert(Vitri2++, tsm);
                }
            }
            regKey.Close();
            
            loadedRcFile = true;   
        }
        
        //Gọi sự kiện click của toolStripMenu recent file
        void tsm_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem tsm=(ToolStripMenuItem)sender;
            string[] fileName = tsm.Text.Split('.');
            string filePath = fileName[1] + ".mdb";
            if (File.Exists(filePath))
            {
                loadFileInDgv(filePath);
            }
            else
            {
                MessageBox.Show("File không tồn tại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                menuOpen_Click(sender, e);
            }
        }

        #region Sự kiện click các button

        public FrmThancongtron frmThantron = null;
        private void menuCongtron_Click(object sender, EventArgs e)
        {
            frmThantron = new FrmThancongtron();
            frmThantron.Show();
            this.Hide();
        }

        public FrmThanhop frmThanhop = null;
        private void menuConghop_Click(object sender, EventArgs e)
        {
            frmThanhop = new FrmThanhop();
            frmThanhop.Show();
            this.Hide();
        }

        public FrmLyTam frmLytam = null;
        private void menuLytam_Click(object sender, EventArgs e)
        {
            frmLytam = new FrmLyTam();
            frmLytam.Show();
            this.Hide();
        }

        public FrmRungloi frmRungloi = null;
        private void menuRungloi_Click(object sender, EventArgs e)
        {
            frmRungloi = new FrmRungloi();
            frmRungloi.Show();
            this.Hide();
        }
        public FrmTracngang frmTracngang = null;

        private void menuTracngang_Click(object sender, EventArgs e)
        {
            frmTracngang = new FrmTracngang();
            frmTracngang.Show();
            this.Hide();
        }

        public FrmDinhdang frmDinhdang = null;
        private void menuDinhdang_Click(object sender, EventArgs e)
        {
            frmDinhdang = new FrmDinhdang();
            frmDinhdang.Show();
            this.Hide();
        }

        public FrmTuychon frmTuychon = null;
        private void menuThietlap_Click(object sender, EventArgs e)
        {
            frmTuychon = new FrmTuychon();
            frmTuychon.Show();
            //this.Hide();
        }
        
        public FrmTdTc533 frmTdTc533 = null;
        private void menuTdtc533monglien_Click(object sender, EventArgs e)
        {
            frmTdTc533 = new FrmTdTc533();
            frmTdTc533.Show();
            this.Hide();
        }

        public FrmTdTc frmTdTc = null;
        private void menuTdtc533mongroi_Click(object sender, EventArgs e)
        {
            frmTdTc = new FrmTdTc();
            frmTdTc.Show();
            this.Hide();
        }

        public FrmTdTcTn frmTdTcTn = null;
        private void menuTdTcTn_Click(object sender, EventArgs e)
        {
            frmTdTcTn = new FrmTdTcTn();
            frmTdTcTn.Show();
            this.Hide();
        }

        public FrmTdTc78 frmTdTc78 = null;
        private void menuTdtc78mongroi_Click(object sender, EventArgs e)
        {
            frmTdTc78 = new FrmTdTc78();
            frmTdTc78.Show();
            this.Hide();
        }

        public FrmTdTcV frmTdTcV = null;
        private void menuTdtc78monglien_Click(object sender, EventArgs e)
        {
            frmTdTcV = new FrmTdTcV();
            frmTdTcV.Show();
            this.Hide();
        }

        public FrmTchanTn frmTchanTn = null;
        private void menuTuongchanTn_Click(object sender, EventArgs e)
        {
            frmTchanTn = new FrmTchanTn();
            frmTchanTn.Show();
            this.Hide();
        }

        public FrmBaccapTc frmBaccapTc = null;
        private void menuBacnuocTc_Click(object sender, EventArgs e)
        {
            frmBaccapTc = new FrmBaccapTc();
            frmBaccapTc.Show();
            this.Hide();
        }

        public FrmHoThu frmHoThu = null;
        private void menuHothu_Click(object sender, EventArgs e)
        {
            frmHoThu = new FrmHoThu();
            frmHoThu.Show();
            this.Hide();
        }

        public FrmHothuQ frmHothuQ = null;
        private void menuHothu533_Click(object sender, EventArgs e)
        {
            frmHothuQ = new FrmHothuQ();
            frmHothuQ.Show();
            this.Hide();
        }

        public FrmHothu78 frmHothu78 = null;
        private void menuHothu78_Click(object sender, EventArgs e)
        {
            frmHothu78 = new FrmHothu78();
            frmHothu78.Show();
            this.Hide();
        }

        public FrmHoGa frmHoGa = null;
        private void menuHogaBt_Click(object sender, EventArgs e)
        {
            frmHoGa = new FrmHoGa();
            frmHoGa.Show();
            this.Hide();
        }

        public FrmBaccap frmBaccap = null;
        private void menuBacnuoc_Click(object sender, EventArgs e)
        {
            frmBaccap = new FrmBaccap();
            frmBaccap.Show();
            this.Hide();
        }

        public FrmMuongTl frmMuongTl = null;
        private void menuMuongtl_Click(object sender, EventArgs e)
        {
            frmMuongTl = new FrmMuongTl();
            frmMuongTl.Show();
            this.Hide();
        }

        public frmCaoD frmCaoD = null;
        private void menuGhicaodo_Click(object sender, EventArgs e)
        {
            frmCaoD = new frmCaoD();
            frmCaoD.Show();
            this.Hide();
        }

        public FrmDatyeu frmDatyeu = null;
        private void menuDatyeu_Click(object sender, EventArgs e)
        {
            frmDatyeu = new FrmDatyeu();
            frmDatyeu.Show();
            this.Hide();
        }
        public FrmKlpd frmKlpd = null;
        private void menuKlCt_Click(object sender, EventArgs e)
        {
            frmKlpd = new FrmKlpd();
            frmKlpd.Show();
            this.Hide();
        }

        public FrmAbout frmAbout = null;
        private void giớiThiệuDrag2011ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAbout = new FrmAbout();
            frmAbout.Show();
            this.Hide();
        }

        private void menuGhepKl_Click(object sender, EventArgs e)
        {
            ghepKhoiLuong();
        }

        private void btNew_Click(object sender, EventArgs e)
        {
            menuNew_Click(sender, e);
        }

        private void btOpen_Click(object sender, EventArgs e)
        {
            menuOpen_Click(sender, e);
        }

        private void btSaveAs_Click(object sender, EventArgs e)
        {
            menuSave_Click(sender, e);
        }

        private void btImport_Click(object sender, EventArgs e)
        {
            menuGhepKl_Click(sender, e);
        }

        private void btDinhdang_Click(object sender, EventArgs e)
        {
            menuDinhdang_Click(sender, e);
        }

        private void btThietlap_Click(object sender, EventArgs e)
        {
            menuThietlap_Click(sender, e);
        }

        private void btTracngang_Click(object sender, EventArgs e)
        {
            menuTracngang_Click(sender, e);
        }

        private void btCongtron_Click(object sender, EventArgs e)
        {
            menuCongtron_Click(sender, e);
        }

        private void btConghop_Click(object sender, EventArgs e)
        {
            menuConghop_Click(sender, e);
        }

        private void btLytam_Click(object sender, EventArgs e)
        {
            menuLytam_Click(sender, e);
        }

        private void btRungloi_Click(object sender, EventArgs e)
        {
            menuRungloi_Click(sender, e);
        }

        private void btTdtc533mongroi_Click(object sender, EventArgs e)
        {
            menuTdtc533mongroi_Click(sender, e);
        }

        private void btTdtc533monglien_Click(object sender, EventArgs e)
        {
            menuTdtc533monglien_Click(sender, e);
        }

        private void btTdTcTn_Click(object sender, EventArgs e)
        {
            menuTdTcTn_Click(sender, e);
        }

        private void btTdtc78mongroi_Click(object sender, EventArgs e)
        {
            menuTdtc78mongroi_Click(sender, e);
        }

        private void btTdtc78monglien_Click(object sender, EventArgs e)
        {
            menuTdtc78monglien_Click(sender, e);
        }

        private void btBacnuocTc_Click(object sender, EventArgs e)
        {
            menuBacnuoc_Click(sender, e);
        }

        private void btTuongchanTn_Click(object sender, EventArgs e)
        {
            menuTuongchanTn_Click(sender, e);
        }

        private void btHothu_Click(object sender, EventArgs e)
        {
            menuHothu_Click(sender, e);
        }

        private void btHothu533_Click(object sender, EventArgs e)
        {
            menuHothu533_Click(sender, e);
        }

        private void btHothu78_Click(object sender, EventArgs e)
        {
            menuHothu78_Click(sender, e);
        }

        private void btHoga_Click(object sender, EventArgs e)
        {
            menuHogaBt_Click(sender, e);
        }

        private void btBacnuoc_Click(object sender, EventArgs e)
        {
            menuBacnuoc_Click(sender, e);
        }

        private void btMuongTl_Click(object sender, EventArgs e)
        {
            menuMuongtl_Click(sender, e);
        }

        private void btDatyeu_Click(object sender, EventArgs e)
        {
            menuDatyeu_Click(sender, e);
        }

        private void btCaodo_Click(object sender, EventArgs e)
        {
            menuGhicaodo_Click(sender, e);
        }
        private void menuThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void Help_Click(object sender, EventArgs e)
        {

        }
        #endregion

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            bool flag = false;
            try
            {
                if (dataGridView1.SelectedRows.Count >= 0)
                {
                    string Str = dataGridView1.CurrentRow.Cells[0].Value.ToString();
                    if (Str.Trim() != "")
                    {
                        if (Str.Contains("km") || Str.Contains("Km") || Str.Contains("kM"))
                        {
                            Str = Str.Substring(2);
                        }
                        //Kiểm tra xem Lý trình có đúng định dạng không
                        Regex rg = new Regex(@"^(KM)?(\d)+\+\d+(\.)?\d+$");
                        if (!rg.IsMatch(Str))
                        {
                            MessageBox.Show("Lý trình không đúng định dạng");
                            dataGridView1.CurrentRow.Cells[0].Value = "";
                            dataGridView1.CurrentRow.Cells["Id_Loaicong"].Value = "";
                            dataGridView1.EndEdit();
                            flag = false;
                        }
                        else
                        {
                            if (!Str.Contains("KM"))
                            {
                                Str = "KM" + Str;
                                dataGridView1.CurrentRow.Cells[0].Value = Str; //Thêm KM nếu người dùng không nhập KM
                            }
                            
                            flag = true;
                        }
                    }
                    else // Nếu không nhập dữ liệu cho lý trình thì xóa lựa chọn trong combobox
                    {
                        dataGridView1.CurrentRow.Cells["Id_Loaicong"].Value = "";
                        flag = false; 
                    }
                }
            }
            catch (Exception)
            {
               // MessageBox.Show(ex.Message);
            }
            if (flag==true)
            {
                dataGridView1.EndEdit();
                saveData();
            }
            else
            {
                dataGridView1.CancelEdit();
            }
        }

        private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (MessageBox.Show("Bạn thực sự muốn xóa cống này?","Thông báo!",MessageBoxButtons.YesNo,MessageBoxIcon.Question)==DialogResult.Yes)
            {
                dataGridView1.EndEdit();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void dataGridView1_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            saveData();
        }

        // Save dữ liệu
        private void saveData()
        {
            dbLytrinh.updateData("SELECT *FROM tb_Lytrinh");
        }
       
    }
}
